#!usr/bin/python
#-*- coding:utf-8 _*-
"""
@author:xiana
@file: NacosMethods.py
@time: 2021/12/31  2:43 下午
"""
import json

from dubbo.client import NacosRegister
from dubbo.common.constants import DUBBO_NC_PROVIDERS
from dubbo.common.exceptions import RegisterException


class NacosMethods(NacosRegister):

    def get_methods_from_nacos(self, interface, version):
        """
                从nacos中根据interface获取到providers信息,methods信息
                :param interface:
                :param version:
                :return:
                """
        service = DUBBO_NC_PROVIDERS.format(interface, version)
        providers = self.nc.get_service_list(timeout=self.timeout, group_name=self.group_name,
                                             namespace_id=self.namespace_id)
        if not providers or service not in providers:
            raise RegisterException('no providers for service {}'.format(service))
        self.nc.subscribe([], service_name=service)
        services = self.nc.subscribed_local_manager.get_local_instances(service) or {}
        self.close()
        instance_r = None
        for k, v in services.items():
            service = v.__dict__
            instance = service.get('instance')
            instance_r = instance
            if not isinstance(instance, list):  instance = [instance]
            hosts = []
            for ins in instance:
                host = '{}:{}'.format(ins.get('ip'), ins.get('port'))
                hosts.append(host)
            self.hosts[interface] = hosts
        return json.loads(instance_r['metadata']['methodParamType'])
